
(function($,win){

	var VFRules = {
		"*":/.+/,
		"*6-16":/^.{6,16}$/,
		"z":/^[\da-zA-Z_]+$/,
		"n":/^\d+$/,
		"s":/^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]+$/m,
		"s6-18":/^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]{6,18}$/,
		"+int":/^[0-9]*[1-9][0-9]*$/,
		"-int":/^-[0-9]*[1-9][0-9]*$/,
		"int":/^-?\d+$/,
		"!-int":/^\d+$/,
		"!+int":/^((-\d+)|(0+))$/,
		"float":/^(-?\d+)(\.\d+)?$/,
		"+float":/^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/, //正浮点数
		"-float":/^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/,  //负浮点数
		"!+float":/^((-\d+(\.\d+)?)|(0+(\.0+)?))$/, //非正浮点数（负浮点数 + 0）
		"!-float":/^\d+(\.\d+)?$/, //非负浮点数（正浮点数 + 0）
		"p":/^[0-9]{6}$/,
		"m":/^1[0-9][0-9]{9}$/,  ///^13[0-9]{9}$|15[0-9]{9}$|18[0-9]{9}$/
		"e":/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
		"idcard" :/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
		"required":/[^(^\s*)|(\s*$)]/,
		"chinese":/^[\u0391-\uFFE5]+$/
	};

	/**
	 * ValidForm 获取待验证的对象值value
	 */
	$InputFieldValue_ = function($vfObject){
		var vfVal = "",vfTagName = $vfObject[0].tagName.toUpperCase();
		var $vfObject0 = null;
		var $vfObject1 = null;
		if(vfTagName == 'INPUT'){
			var vfType = $vfObject.attr("type").toUpperCase();
			if(vfType == 'CHECKBOX' || vfType == 'RADIO'){
				$vfObject0 = $vfObject.parents("form").find("input[name='"+$vfObject.attr("name")+"']");
				$vfObject1 = $vfObject0.filter(":checked");
				if(vfType == 'RADIO'){
					vfVal = $vfObject1.val();
				}else{
					vfVal = [];
					$.each($vfObject1,function(k,item_){
						vfVal.push($(item_).val());
					});
				}
			}else{
				vfVal = $vfObject.val();
			}
		}else if(vfTagName == 'SELECT'){
			vfVal = $vfObject.val();
		}else{
			vfVal = $vfObject.val();
		}
		return vfVal;
	};

	$InputFieldCheck_ = function($vfObject, vfVal, vfRules){
		var vfRule = vfRules["rule"];
		var vfMsg = vfRules['msg'];
		var vfNull = vfRules['inull'];
		if(!(vfRule instanceof Array) || vfRule.length <= 0){ return true; }

		var isAllPass = true;
		var cresult_ = "";
		$.each(vfRule,function(k,item){
			var isPass = false;
			if(typeof(VFRules[item])!='undefined'){
				if(vfNull && (!vfVal || vfVal == "")){
					isPass = true;
				}else{
					if($.isFunction(VFRules[item])){
						isPass = (VFRules[item])(vfVal, $vfObject);
					}else{
						isPass = (VFRules[item]).test(vfVal);
					}
				}
			}else{
				isPass = false;
				if(typeof(item) == 'string' && $.trim(item)!='' && item.length>4
					&& ",*,s,n,z,".indexOf(","+item.charAt(0)+",")!=-1
					&& (item.charAt(1) == '[')
					&& (item.charAt(item.length - 1) == ']')){
					var find = new RegExp("\\[[\\d\\-]*\\]").exec(item);
					if(find){
						find = find[0].replace("-",",").replace("[","").replace("]","");
						var reg = null;
						switch (item.charAt(0)) {
							case '*':
								reg = new RegExp("^.{"+find+"}$");
								break;
							case 's':
								reg = new RegExp("^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]{"+find+"}$");
								break;
							case 'n':
								reg = new RegExp("^\\d{"+find+"}$");
								break;
							case 'z':
								reg = new RegExp("^[\\da-zA-Z_]{"+find+"}$");
								break;
							default:
								break;
						}
						if(reg!=null){
							isPass = reg.test(vfVal);
						}
					}
				}
			}
			if(isAllPass)
				isAllPass = !isPass ? false : true;
			if(!isPass){
				var vfMessage = !vfMsg[k] ? "验证失败!" : vfMsg[k];
				cresult_ += "<li>"+vfMessage+"</li>";
			}
		});
		return cresult_;
	};

	$.fn.VForm = function(settings){
		if(!settings){
			settings = {
				rules:{}, ajaxpost: false, callback : function(data){}
			};
		}
		VFRules = $.extend({},VFRules, (settings.rules ? settings.rules : {}));
		var $VForm_ = $(this);

		/**
		 * blur验证带有d-valid属性对象
		 * {target:"name", rule:["*","*6-16"], msg:["用户名不能为空!","用户名长度为6-16"], inull:true}
		 inull 是验证空值， 作用于  rule:["!-int"]这样直接验证value，但允许为空的情况。
		 */
		$VForm_.find('*[d-valid]').blur(function(){
			var this_ = $(this);
			var dvalid_ = this_.attr("d-valid"); //验证json数据
			var dpholder_ = this_.attr("d-pholder"); //默认值

			var cvalue_ = $InputFieldValue_(this_);
			if(dpholder_ == cvalue_){ cvalue_ = ""; }
			this_.closest('.field').find(".input-help").remove();

			eval("var jdata_ = " + dvalid_ + ";");
			var cresult_ = $InputFieldCheck_(this_, cvalue_, jdata_);
			if(cresult_ == ''){
				this_.closest('.form-group').removeClass("check-error");
				this_.parent().find(".input-help").remove();
				this_.closest('.form-group').addClass("check-success");
			}else{
				this_.closest('.form-group').removeClass("check-success");
				this_.closest('.form-group').addClass("check-error");
				this_.closest('.field').append('<div class="input-help"><ul>'+cresult_+'</ul></div>');
			}
		});

		/**
		 * 表单提交验证
		 */
		$VForm_.submit(function(){
			$(this).find('*[d-valid]').trigger("blur");
			//$(this).find('input[placeholder],textarea[placeholder]').each(function(){$hideplaceholder($(this));});
			var numError = $(this).find('.check-error').length;
			if(numError){
				$(this).find('.check-error').first().find('*[d-valid]').first().focus().select();
				return false;
			}
			if(settings.ajaxpost){
				var url = $(this).attr("action");
				$.ajax({
					url: url,
					type: "POST",
					async: true,
					data: $(this).serializeArray(),
					success: function (jdata) {
						settings.callback(jdata);
					},
					error:function(){
						alert("请求失败");
					}
				});
				return false;
			}
			return true;
		});
	};

})(jQuery,window);

$(function(){

	$("*[d-pholder]").each(function(index, element){
		var content=false;
		if($(this).val().length === 0 || $(this).val()==$(this).attr("d-pholder")){content=true};
		if(content){
			$(element).val($(element).attr("d-pholder"));
			$(element).css("color","rgb(169,169,169)");
			$(element).data("pholder",$(element).css("color"));
			if($(element).attr("type")=="password"){
				$(element).attr("type", "text");
				$(element).attr("d-type", "password");
			}
			$(element).focus(function(){
				if($(element).attr("d-type")=="password"){
					$(element).attr("type", "password");
				}
				$HidePlaceholder_($(this));
			});
			$(element).blur(function(){
				$ShowPlaceholder_($(this));
			});
		}
	});

	var $ShowPlaceholder_ = function(element){
		if(($(element).val().length ===0 || $(element).val()==$(element).attr("d-pholder"))){
			if($(element).attr("d-type")=="password"){
				$(element).attr("type", "text");
			}
			$(element).val($(element).attr("d-pholder"));
			$(element).data("pholder",$(element).css("color"));
			$(element).css("color","rgb(169,169,169)");
		}
	};

	var $HidePlaceholder_ = function(element){
		if($(element).data("pholder")){
			if($(element).attr("d-type")=="password"){
				$(element).attr("type", "password");
			}
			$(element).val("");
			$(element).css("color", $(element).data("pholder"));
			$(element).removeData("pholder");
		}
	};
	
	/**
	 * 重置form
	 */
	$('.form-reset').click(function(){
		$(this).closest('form').find(".input-help").remove();
		$(this).closest('form').find('.form-submit').removeAttr('disabled');
		$(this).closest('form').find('.form-group').removeClass("check-error");
		$(this).closest('form').find('.form-group').removeClass("check-success");
	});
	/*
	$pintuercheck=function(element,type,value){
		$pintu=value.replace(/(^\s*)|(\s*$)/g, "");
		switch(type){
			case "required":return /[^(^\s*)|(\s*$)]/.test($pintu);break;
			case "chinese":return /^[\u0391-\uFFE5]+$/.test($pintu);break;
			case "number":return /^\d+$/.test($pintu);break;
			case "integer":return /^[-\+]?\d+$/.test($pintu);break;
			case "plusinteger":return /^[+]?\d+$/.test($pintu);break;
			case "double":return /^[-\+]?\d+(\.\d+)?$/.test($pintu);break;
			case "plusdouble":return /^[+]?\d+(\.\d+)?$/.test($pintu);break;
			case "english":return /^[A-Za-z]+$/.test($pintu);break;
			case "username":return /^[a-z]\w{3,}$/i.test($pintu);break;
			case "mobile":return /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[89]\d{8}?$|170\d{8}?$|147\d{8}?$/.test($pintu);break;
			case "phone":return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/.test($pintu);break;
			case "tel":return /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[89]\d{8}?$|170\d{8}?$|147\d{8}?$/.test($pintu) || /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/.test($pintu);break;
			case "email":return /^[^@]+@[^@]+\.[^@]+$/.test($pintu);break;
			case "url":return /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test($pintu);break;
			case "ip":return /^[\d\.]{7,15}$/.test($pintu);break;
			case "qq":return /^[1-9]\d{4,10}$/.test($pintu);break;
			case "currency":return /^\d+(\.\d+)?$/.test($pintu);break;
			case "zip":return /^[1-9]\d{5}$/.test($pintu);break;
			case "radio":
				var radio=element.closest('form').find('input[name="'+element.attr("name")+'"]:checked').length;
				return eval(radio==1);
				break;
			default:
				var $test=type.split('#');
				if($test.length>1){
					switch($test[0]){
						case "compare":
							return eval(Number($pintu)+$test[1]);
							break;
						case "regexp":
							return new RegExp($test[1],"gi").test($pintu);
							break;
						case "length":
							var $length;
							if(element.attr("type")=="checkbox"){
								$length=element.closest('form').find('input[name="'+element.attr("name")+'"]:checked').length;
							}else{
								$length=$pintu.replace(/[\u4e00-\u9fa5]/g,"***").length;
							}
							return eval($length+$test[1]);
							break;
						case "ajax":
							var $getdata;
							var $url=$test[1]+$pintu;
							$.ajaxSetup({async:false});
							$.getJSON($url,function(data){
								$getdata=data.getdata;
							});
							if($getdata=="true"){return true;}
							break;
						case "repeat":
							return $pintu==jQuery('input[name="'+$test[1]+'"]').eq(0).val();
							break;
						default:return true;break;
					}
					break;
				}else{
					return true;
				}
		}
	};
	*/
});